
import { cache } from "@/utils/cache";
import config from "@/config/index";
// 读取环境配置
const AppConfig = window.AppConfig;

/**
 * 获取目标路由
 * @param 目标路由 path 
 * @param 参数 query 
 */
export function getTargetPath(path = "", query = "") {
    if (path && query) {
        return { path: path, query: { ...query } };
    }
    if (path && !query) {
        return { path: path };
    }

    const getEndSon = (data) => {

        const endSon = (list, selectedKey) => {
            let item = undefined;
            if (list.length == 0) {
                return {
                    item,
                    selectedKey
                };
            }
            let new_list = [];
            for (const key in list) {
                if (!list[key]["hidden"]) {
                    new_list.push(list[key]);
                }
            }
            item = new_list[0];
            if (item["children"] && item["children"].length > 0) {
                if (item.path) {
                    selectedKey.push(item.path);
                }
                return endSon(item["children"], selectedKey);
            }
            return {
                item,
                selectedKey
            };
        }

        const endSonObj = endSon(data, []);
        const endSonItem = endSonObj.item;
        if (!endSonItem) {
            return "";
        }
        const selectedKey = endSonObj.selectedKey;
        cache("selectedKey_" + config.MenuCacheName, selectedKey, 86400);
        return endSonItem.path ? endSonItem.path : "";
    }
    const list = cache(config.MenuCacheName);
    const initPath = getEndSon(list);
    if (!initPath) {
        return { path: AppConfig.LOGIN_PATH };
    }
    return { path: initPath };
}